#!/bin/bash

# this is executed in the docker fpm image
set -e
cd /build

# the init scripts needs to have the right name
cp ${RUNID}.init /tmp/{{.beat_pkg_name}}.init

# create script to reload systemd config
echo "#!/bin/bash" > /tmp/systemd-daemon-reload.sh
echo "systemctl daemon-reload 2> /dev/null || true" >> /tmp/systemd-daemon-reload.sh

# add SNAPSHOT if it was requested
VERSION="{{.version}}"
if [ "$SNAPSHOT" = "yes" ]; then
    VERSION="${VERSION}-SNAPSHOT"
fi

# fpm replaces - with _ in the version
RPM_VERSION=`echo ${VERSION} | sed 's/-/_/g'`

# create rpm
FPM_ARGS=(
        --force -s dir -t rpm
        -n {{.beat_pkg_name}} -v ${RPM_VERSION}
        --architecture {{.rpm_arch}}
        --vendor "{{.beat_vendor}}"
        --license "{{.beat_license}}"
        --description "{{.beat_description}}"
        --url {{.beat_url}}
        --rpm-init /tmp/{{.beat_pkg_name}}.init
        --after-install /tmp/systemd-daemon-reload.sh
        --config-files /etc/{{.beat_name}}/{{.beat_name}}.yml
        homedir/=/usr/share/{{.beat_name}}
        beatname-${RUNID}.sh=/usr/bin/{{.beat_name}}
        {{.beat_name}}-linux-{{.arch}}=/usr/share/{{.beat_name}}/bin/{{.beat_name}}
        {{.beat_name}}-linux.yml=/etc/{{.beat_name}}/{{.beat_name}}.yml
        {{.beat_name}}-linux.reference.yml=/etc/{{.beat_name}}/{{.beat_name}}.reference.yml
        fields.yml=/etc/{{.beat_name}}/fields.yml
        ${RUNID}.service=/lib/systemd/system/{{.beat_pkg_name}}.service
        god-linux-{{.arch}}=/usr/share/{{.beat_name}}/bin/{{.beat_name}}-god
  )

if [ -d modules.d-linux ]; then
  FPM_ARGS+=(modules.d-linux/=/etc/{{.beat_name}}/modules.d/)
fi

fpm "${FPM_ARGS[@]}"

# rename so that the filename respects semver rules
mkdir -p upload
mv {{.beat_pkg_name}}-${RPM_VERSION}-1.{{.rpm_arch}}.rpm upload/{{.beat_name}}-${VERSION}-{{.rpm_arch}}.rpm
echo "Created upload/{{.beat_name}}-${VERSION}-{{.rpm_arch}}.rpm"

# create sha1 file
cd upload
sha1sum {{.beat_name}}-${VERSION}-{{.rpm_arch}}.rpm | awk '{print $1;}' > {{.beat_name}}-${VERSION}-{{.rpm_arch}}.rpm.sha1
echo "Created upload/{{.beat_name}}-${VERSION}-{{.rpm_arch}}.rpm.sha1"
